<template>
  <div class="addExam">
    <el-dialog
      :title="addOrEdit === 'add' ? '新增A类考试': addOrEdit === 'edit' ? '编辑A类考试' :'查看A类考试'"
      :fullscreen='true'
      :visible.sync="examTestVisible"
      width="30%"
      :before-close="handleClose">
      <div class="body-box">
        <div class="top">
          <div class="top-inner">
            <el-steps :active="activeIndex" align-center>
              <el-step title="第一步" description="添加考试信息"></el-step>
              <el-step title="第二步" :description="firstForm.ifAnonymous === '1' ?'添加考站、考官、考题、匿名考生': '添加考站、考官、考题' "></el-step>
              <el-step title="第三步" :description="firstForm.ifAnonymous === '1' ?'预览': '添加考生' "></el-step>
              <el-step v-if="firstForm.ifAnonymous !== '1'" title="第四步" description="预览"></el-step>
            </el-steps>
          </div>
        </div>
        <div class="mid">
          <div class="mid-inner">
            <div v-if="activeIndex === 0">
              <el-form :model="firstForm" :rules="firstRules" ref="firstForm" label-width="150px" v-if="firstForm">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="选择学生库" prop="studentPool">
                      <div style="display: flex;justify-content: space-between;align-items: center;height: 36px;">
                        <div>
                          <p v-if="!firstForm.studentPool" style="color: #999;">暂无考生库 <span class='icon iconfont icon-xinxi' style="padding-left: 4px;"></span></p>
                          <p v-else style="color: #00b99e;">{{ firstForm.studentPool }} <span class='icon iconfont icon-tongguo' style="padding-left: 4px;"></span></p>
                        </div>
                        <el-button v-if="addOrEdit !== 'view'" type="primary" @click="chooseStudent">{{ firstForm.studentPool? '重新选择学生库' : '添加学生库' }}</el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="选择考官库" prop="teacherPool">
                      <div style="display: flex;justify-content: space-between;align-items: center;height: 36px;">
                        <div>
                          <p v-if="!firstForm.teacherPool" style="color: #999;"> 暂无考官库 <span class='icon iconfont icon-xinxi' style="padding-left: 4px;"></span></p>
                          <p v-else style="color: #00b99e;">{{ firstForm.teacherPool }}  <span class='icon iconfont icon-tongguo' style="padding-left: 4px;"></span></p>
                        </div>
                        <el-button v-if="addOrEdit !== 'view'" type="primary" @click="chooseTeacher">{{ firstForm.teacherPool? '重新选择考官库' : '添加考官库' }}</el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="选择总裁判" prop="teacherId">
                      <el-select v-model="firstForm.teacherId" placeholder="请选择" :disabled="addOrEdit === 'view'" style="width: 260px;" :filterable="true" :clearable="true">
                        <el-option
                          v-for="item in teacherArr"
                          :key="item.id"
                          :label="item.teacherName"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="考试名称" prop="recordsName">
                      <el-input v-model="firstForm.recordsName" placeholder="请输入考试名称" :readonly="addOrEdit === 'view'"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="考点名称" prop="examLocation">
                      <el-input v-model="firstForm.examLocation" placeholder="请输入考点名称" :readonly="addOrEdit === 'view'"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="考题时长" prop="sountdownTime">
                      <el-input v-model="firstForm.sountdownTime" placeholder="请填写考题时长" type="number" :readonly="addOrEdit === 'view'">
                        <template slot="append">分钟</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="使用考站数量" prop="stationNumber">
                      <el-select v-model="firstForm.stationNumber" placeholder="请选择" :disabled="addOrEdit === 'view'">
                        <el-option
                          v-for="item in stationNumberOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="考点地址" prop="examAddress">
                      <el-input v-model="firstForm.examAddress" placeholder="请输入考点地址" :readonly="addOrEdit === 'view'"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="选择大小分项" prop="examScoreSet">
                      <el-select v-model="firstForm.examScoreSet" placeholder="请选择" :disabled="addOrEdit === 'view'">
                        <el-option
                          v-for="item in examScoreSetOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="选择考题库" prop="examPoolId">
                      <el-select @change="changeExamLibrary" v-model="firstForm.examPoolId" placeholder="请选择" :filterable="true" :disabled="addOrEdit === 'view'">
                        <el-option
                          v-for="item in examPoolIdOptions"
                          :key="item.id"
                          :label="item.examPool"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="考试日期" prop="examDate">
                        <el-date-picker
                          :readonly="true"
                          :disabled="addOrEdit === 'view'"
                          :picker-options="pickerOptions"
                          @change="dateChange"
                          style='width: 100%'
                          value-format="yyyy-MM-dd"
                          v-model="firstForm.examDate"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="考试总计">
                      <div v-if="firstForm.examDate && firstForm.examDate.length > 0"> {{daysBetween(firstForm.examDate[0],firstForm.examDate[1])}}天</div>
                      <div v-else>暂无</div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                      <el-form-item label="预计考试时间" prop="examDate">
                        <el-form ref="addFormRef" :model="addFormData" :rules="addFormRules" size="mini" :inline="true" >
                          <el-table tooltip-effect="light" :data="addFormData.productList" class='inline-table custom-table' :row-class-name="tableRowClassName">
                              <el-table-column label="考试日期" prop="examDateDay" min-width="100" align="center">
                                  <template slot-scope="scope">
                                      <el-form-item size="small" :prop="'productList.' + scope.$index + '.examDateDay'"
                                          :rules="addFormRules.examDateDay" class="all">
                                          <el-select v-model="scope.row.examDateDay" :readonly='true' placeholder="请选择">
                                            <el-option
                                              v-for="item in dateOptions"
                                              :key="item.value"
                                              :label="item.label"
                                              :value="item.value">
                                            </el-option>
                                          </el-select>
                                      </el-form-item>
                                  </template>
                              </el-table-column>
                              <el-table-column label="考试时间" prop="examDateRange" min-width="200" align="center">
                                  <template slot-scope="scope">
                                      <el-form-item size="small" :prop="'productList.' + scope.$index + '.examDateRange'"
                                          :rules="addFormRules.examDateRange" class="all" >
                                          <div style="display: flex">
                                            <el-time-select
                                              style="width: 140px;margin-right: 20px;"
                                              placeholder="起始时间"
                                              v-model="scope.row.startTime"
                                              :readonly='true'
                                              :picker-options="{
                                                start: '08:30',
                                                step: '00:15',
                                                end: '18:30'
                                              }">
                                            </el-time-select>
                                            <div style="padding: 0 16px 0 0;">到</div>
                                            <el-time-select
                                              style="width: 140px;"
                                              placeholder="结束时间"
                                              v-model="scope.row.endTime"
                                              :readonly='true'
                                              :picker-options="{
                                                start: '08:30',
                                                step: '00:15',
                                                end: '18:30',
                                                minTime: scope.row.startTime
                                              }">
                                            </el-time-select>
                                          </div>
                                      </el-form-item>
                                  </template>
                              </el-table-column>
                              <el-table-column label="组数" prop="teamCount" min-width="100" align="center">
                                  <template slot-scope="scope">
                                      <el-form-item size="small" :prop="'productList.' + scope.$index + '.examDateDay'"
                                          :rules="addFormRules.examDateDay" class="all">
                                          <el-select v-model="scope.row.teamCount" :readonly='true' placeholder="请选择组数" @change="teamCountChange(scope.row)" :disabled="addOrEdit === 'view' || scope.$index != '0'">
                                            <el-option
                                              v-for="item in teamCountOptions"
                                              :key="item.value"
                                              :label="item.label"
                                              :value="item.value">
                                            </el-option>
                                          </el-select>
                                      </el-form-item>
                                  </template>
                              </el-table-column>
                          </el-table>
                        </el-form>
                      </el-form-item>
                    </el-col>
                  <el-col :span="12">
                    <el-form-item label="设置最小分值" prop="examScoreMin">
                      <el-select v-model="firstForm.examScoreMin" size="small" :disabled="addOrEdit === 'view'">
                          <el-option v-for="(item,index) in examScoreMinOptions" :key="index" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否匿名考试" prop="ifAnonymous">
                      <el-select v-model="firstForm.ifAnonymous" size="small" :disabled='true'>
                          <el-option v-for="(item,index) in onOrOffOptions" :key="index" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否考官签名" prop="ifSign">
                      <el-select v-model="firstForm.ifSign" size="small" :disabled="addOrEdit === 'view'">
                          <el-option v-for="(item,index) in onOrOffOptions" :key="index" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否启用倒计时" prop="ifSountdown">
                      <el-select v-model="firstForm.ifSountdown" size="small" :disabled="addOrEdit === 'view'">
                          <el-option v-for="(item,index) in onOrOffOptions" :key="index" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="是否需要密码：" prop="passwordType">
                      <!-- {{ exercisesForm.passwordType   true: 1 需要密码   false： 0 不需要密码 }} -->
                      <el-switch
                        v-model="firstForm.passwordType"
                        :disabled="(firstForm.id && firstForm.createUserId !== userInfo.id) || addOrEdit === 'view'"
                        active-text="需要"
                        inactive-text="不需要">
                      </el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="密码" prop="password" v-if="firstForm.passwordType == true">
                      <el-input type="password" v-model="firstForm.password" autocomplete="off" placeholder="请输入密码" :disabled="(firstForm.id && firstForm.createUserId !== userInfo.id) || addOrEdit === 'view'"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="确认密码" prop="checkPassword" v-if="firstForm.passwordType == true">
                      <el-input type="password" v-model="firstForm.checkPassword" autocomplete="off" placeholder="请再次输入密码" :disabled="(firstForm.id && firstForm.createUserId !== userInfo.id) || addOrEdit === 'view'"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form> 
              <el-dialog
                class='new-dialog'
                title="选择考生库"
                :visible.sync="chooseStudentShow"
                width="700px"
                :append-to-body='true'>
                <div class="newBox">
                  <div class="flex" style="margin-bottom: 10px; justify-content: flex-start;">
                    <el-input placeholder="考生库名称" v-model="searchText" style="width: 260px;margin-right: 10px;"/>
                    <el-button type="primary" @click="getList">搜 索</el-button>
                  </div>
                  <el-table
                    size='mini'
                    :data="studentPoolArr"
                    @cell-click='chooseHandle'
                    border
                    style="width: 100%;height: 360px">
                    <el-table-column
                      prop="studentPool"
                      label="考生库名称"
                      align='center'
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="studentNumber"
                      label="考生数"
                      align='center'
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="creatDate"
                      align='center'
                      label="创建时间">
                    </el-table-column>
                  </el-table>
                </div>
              </el-dialog>
              <el-dialog
                class='new-dialog'
                title="选择考官库"
                :visible.sync="chooseTeacherShow"
                width="700px"
                :append-to-body='true'>
                <div class="newBox">
                  <div class="flex" style="margin-bottom: 10px; justify-content: flex-start;">
                    <el-input placeholder="考官库名称" v-model="searchTeacherText" style="width: 260px;margin-right: 10px;"/>
                    <el-button type="primary" @click="getTeacherList">搜 索</el-button>
                  </div>
                  <el-table
                    size='mini'
                    :data="teacherPoolArr"
                    @cell-click='chooseTeacherHandle'
                    border
                    style="width: 100%;height: 360px">
                    <el-table-column
                      prop="teacherPool"
                      label="考官库名称"
                      align='center'
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="teacherNumber"
                      label="考官数"
                      align='center'
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="creatDate"
                      align='center'
                      label="创建时间">
                    </el-table-column>
                  </el-table>
                </div>
              </el-dialog>
            </div>
            <div v-if="activeIndex === 1">
              <secondStep :addOrEdit="addOrEdit" :passwordCheck='passwordCheck' ref='secondStep' :recordsStationOptions="recordsStationOptions" :teacherOptions='teacherOptions' :recordsId='recordsId' :examOptions='examOptions' @secondHandleEnd='secondHandleEnd' @secondHandleEndNiMing='secondHandleEndNiMing'></secondStep>
            </div>
            <div v-if="activeIndex === 2 && firstForm.ifAnonymous === '0'">
              <thirdStep :addOrEdit="addOrEdit" :passwordCheck='passwordCheck' ref='thirdStep' :recordsId='recordsId' :studentPoolId='firstForm.studentPoolId' @changeTab="changeTab"></thirdStep>
            </div>
            <div v-if="(activeIndex === 2 && firstForm.ifAnonymous === '1') || (activeIndex === 3 && firstForm.ifAnonymous === '0')">
              <forthStep :addOrEdit="addOrEdit" :passwordCheck='passwordCheck' ref='forthStep' :recordsStationOptions="recordsStationOptions" :teacherOptions='teacherOptions' :recordsId='recordsId' :examOptions='examOptions'></forthStep>
            </div>
          </div>
        </div>
        <div class="bot">
          <div class="bot-inner flex" v-if="activeIndex === 0">
            <el-button type="primary" @click="firstViewSubmit" v-if="addOrEdit === 'view'">查看下一步</el-button>
            <el-button type="primary" @click="firstSubmit" v-else>下一步</el-button>
          </div>
          <div class="bot-inner flex" v-if="activeIndex === 1">
            <el-button @click="activeIndex = 0" v-if="addOrEdit !== 'add'">返回第一步</el-button>
            <el-button type="primary" @click="secondViewSubmit" v-if="addOrEdit === 'view'">查看下一步</el-button>
            <el-button v-if="firstForm.ifAnonymous == 0 && addOrEdit !== 'view'" type="primary" @click="secondSubmit">下一步</el-button>
            <el-button v-if="firstForm.ifAnonymous == 1 && addOrEdit !== 'view'" type="primary" @click="recordsSubmitBefore">下一步</el-button>
            <!-- <el-button v-if="firstForm.ifAnonymous == 1" type="primary" @click="recordsSubmit">匿名添加考生并预览</el-button> -->
          </div>
          <!-- <div class="bot-inner flex" v-if="activeIndex === 2">
            <el-button @click="activeIndex = 1">返回第二步</el-button>
            <el-button type="primary" @click="thirdSubmit">保存及预览</el-button>
          </div> -->
          <div class="bot-inner flex" v-if="firstForm.ifAnonymous == 0 && activeIndex === 3">
            <el-button @click="handleClose">关闭</el-button>
          </div>
          <div class="bot-inner flex" v-if="firstForm.ifAnonymous == 1 && activeIndex === 2">
            <el-button @click="handleClose">关闭</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import secondStep from './secondStep.vue'
import thirdStep from './thirdStep.vue'
import forthStep from './forthStep.vue'
import {recordsDetail, saveRecordsFirst, updateRecordsFirst, recordsDateDelete} from '@/api/examTest.js'
import {fetchList, examRecordsSubmitA, fetchTeacherList} from '@/api/examinee.js'
// 考官库
import { studentList } from '@/api/examiner.js'
import * as testLibrary from '@/api/testLibrary.js'
import * as examStation from '@/api/examStation.js'
import moment from 'moment'
export default{
  props: ['examTestVisible', 'addOrEdit', 'passwordCheck'],
  components: {
    secondStep,
    thirdStep,
    forthStep
  },
  data () {
    var validatePass = (rule, value, callback) => {
      console.log('value', value)
      if (value === '' || value === null) {
        callback(new Error('请输入密码'))
      } else {
        if (this.firstForm.password !== '') {
          this.$refs.firstForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.firstForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      teacherArr: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now()
        }
      },
      // 大小分项
      examScoreSetOptions: [
        {
          label: '大分项',
          value: '1'
        },
        {
          label: '小分项',
          value: '2'
        }
      ],
      // 考题库
      examPoolIdOptions: [],
      dateOptions: [],
       // id备份
      recordsId: '',
      // 考点
      recordsStationOptions: [],
      teacherOptions: [],
      examOptions: [],
      activeIndex: null,
      firstStepInfo: {},
      firstStepDataList: [],
      searchText: '',
      studentPoolArr: [],
      chooseStudentShow: false,
      searchTeacherText: '',
      teacherPoolArr: [],
      chooseTeacherShow: false,
      stationNumberOptions: [
        {
          label: '1个',
          value: 1
        },
        {
          label: '2个',
          value: 2
        },
        {
          label: '3个',
          value: 3
        },
        {
          label: '4个',
          value: 4
        },
        {
          label: '5个',
          value: 5
        },
        {
          label: '6个',
          value: 6
        },
        {
          label: '7个',
          value: 7
        },
        {
          label: '8个',
          value: 8
        },
        {
          label: '9个',
          value: 9
        },
        {
          label: '10个',
          value: 10
        }
      ],
      teamCountOptions: [
        {
          label: '总共一组',
          value: 1
        },
        {
          label: '总共两组',
          value: 2
        },
        {
          label: '总共三组',
          value: 3
        }
      ],
      onOrOffOptions: [
        {
          label: '启用',
          value: '1'
        },
        {
          label: '不启用',
          value: '0'
        }
      ],
      examScoreMinOptions: [
        {
          label: '0.1',
          value: '0.1'
        },
        {
          label: '0.5',
          value: '0.5'
        },
        {
          label: '1',
          value: '1'
        }
      ],
      firstForm: {},
      addFormData: {
        // 产品列表
        productList: [
          {
            examDateDay: '',
            startTime: '',
            endTime: ''
          }
        ]
      },
      addFormRules: {
        examDateDay: [{
          required: true,
          message: '请选择考试日期',
          trigger: 'blur'
        }]
      },
      firstRules: {
        recordsName: [
          { required: true, message: '请输入考试名称', trigger: ['blur'] },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: ['blur'] }
        ],
        examLocation: [
          { required: true, message: '请输入考点名称', trigger: ['blur'] },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: ['blur'] }
        ],
        sountdownTime: [
          { required: true, message: '考题时长不能为空', trigger: ['blur'] }
        ],
        examAddress: [
          { required: true, message: '请输入考点地址', trigger: ['blur'] },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: ['blur'] }
        ],
        examScoreSet: [
          { required: true, message: '请选择大小分项', trigger: ['blur'] }
        ],
        examPoolId: [
          { required: true, message: '请选择考题库', trigger: ['blur'] }
        ],
        examDate: [
          { required: true, message: '请选择考试起止时间', trigger: ['blur'] }
        ],
        studentPool: [
          { required: true, message: '请选择考生库', trigger: ['blur', 'change'] }
        ],
        teacherPool: [
          { required: true, message: '请选择考官库', trigger: ['blur', 'change'] }
        ],
        ifSountdown: [
          { required: true, message: '选择是否启用倒计时', trigger: ['blur', 'change'] }
        ],
        ifSign: [
          { required: true, message: '选择是否签名', trigger: ['blur', 'change'] }
        ],
        ifAnonymous: [
          { required: true, message: '选择是否匿名', trigger: ['blur', 'change'] }
        ],
        stationNumber: [
          { required: true, message: '选择考站数量', trigger: ['blur', 'change'] }
        ],
        // teacherId: [
        //   { required: true, message: '选择总裁判', trigger: ['blur', 'change'] }
        // ],

        password: [
            { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
            { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      userInfo: this.$store.state.user
    }
  },
  methods: {
    teamCountChange (val) {
      this.addFormData.productList.map(v => {
        v.teamCount = val.teamCount
      })
    },
    // 获取考官库
    getTeacher () {
      let params = {
        page: 1,
        limit: 2000,
        teacherPoolId: this.firstForm.teacherPoolId,
        orderSql: 'creat_date desc'
      }
      studentList(params).then(res => {
        this.teacherArr = res.data.page.records
        console.log(res)
      })
    },
    // 获取考题库
    getTestLibrary () {
      console.log('zxk')
      let params = {
        limit: 1000,
        page: 1
      }
      testLibrary.fetchList(params).then(res => {
        this.examPoolIdOptions = res.data.page.records
      })
    },
    tableRowClassName ({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    },
    dateChange (val) {
      let days = this.daysBetween(val[0], val[1])
      let arr = []
      for (let i = 0; i < days; i++) {
        arr.push(moment(new Date(val[0]).getTime() + 24 * 60 * 60 * 1000 * i).format('YYYY-MM-DD'))
      }
      this.addFormData = {
        productList: []
      }
      this.dateOptions = []
      arr.map(item => {
        this.dateOptions.push({
          label: item,
          value: item
        })
        this.addFormData.productList.push({
          examDateDay: item,
          startTime: '09:00',
          endTime: '12:00'
        })
        this.addFormData.productList.push({
          examDateDay: item,
          startTime: '14:00',
          endTime: '17:00'
        })
      })
    },
    dateRange (val1, val2) {
      let days = this.daysBetween(val1, val2)
      let arr = []
      for (let i = 0; i < days; i++) {
        arr.push(moment(new Date(val1).getTime() + 24 * 60 * 60 * 1000 * i).format('YYYY-MM-DD'))
      }
      this.addFormData = {
        productList: []
      }
      this.dateOptions = []
      arr.map(item => {
        this.dateOptions.push({
          label: item,
          value: item
        })
        this.addFormData.productList.push({
          examDateDay: item,
          startTime: '09:00',
          endTime: '12:00'
        })
        this.addFormData.productList.push({
          examDateDay: item,
          startTime: '14:00',
          endTime: '17:00'
        })
      })
    },
    groupBy (array, key) {
      return array.reduce((result, currentItem) => {
        // 使用 Map 对象来存储分组后的数据
        const keyValue = currentItem[key]
        if (!result.has(keyValue)) {
          result.set(keyValue, [currentItem])
        } else {
          result.get(keyValue).push(currentItem)
        }
        return result
      }, new Map())
    },
    // 获取考点
    getExamStation () {
      examStation.fetchList({page: 1, limit: 1000, orderSql: 'station_number asc'}).then(res => {
        this.recordsStationOptions = res.data.page.records
      })
    },

    changeExamLibrary () {
      this.getExamList()
    },

    // 获取考试试题
    // TODO 修改成考题库里面的考题
    getExamList () {
      testLibrary.examinationList({ page: 1, limit: 1000, examPoolId: this.firstForm.examPoolId }).then(res => {
        this.examOptions = res.data.page.records
      })
    },

    handleClose () {
      this.$emit('closeHandle', 'fresh')
    },
    // 第一步查看
    firstViewSubmit () {
      let examRecordsEntity = JSON.parse(JSON.stringify(this.firstForm))
      setTimeout(() => {
        this.activeIndex = 1
        if (this.firstForm.passwordType) {
          this.passwordCheck = this.firstForm.password
        }
        this.recordsId = examRecordsEntity.id
        setTimeout(() => {
          this.$refs.secondStep.getRecordsDetail2()
        }, 10)
      }, 10)
    },
    // 第一步保存
    firstSubmit () {
      this.submitFirstHandle()
    },
    // 获取考题详情
    getRecordsDetail (id) {
      if (id) {
        let params = {
          id: id
        }
        if (this.passwordCheck !== '') {
          params.password = this.passwordCheck
          params.passwordType = '1'
        } else {
          params.passwordType = '0'
        }
        recordsDetail(params).then(res => {
          this.firstForm = res.data.examRecordsDtos[0].examRecordsEntity
          this.firstStepDataList = res.data.examRecordsDtos[0].examRecordsDates
          if (res.data.examRecordsDtos[0].examRecordsEntity.passwordType === '1') {
            this.firstForm.passwordType = true
            this.firstForm.password = this.passwordCheck
            this.firstForm.checkPassword = this.passwordCheck
          } else {
            this.firstForm.passwordType = false
          }
          let aaa = JSON.parse(JSON.stringify(this.firstForm))
          this.firstForm = {}
          this.firstForm = JSON.parse(JSON.stringify(aaa))
          this.getTeacher()
          this.activeIndex = 0
          this.changeFirstInfo()
          this.getExamList()
        })
      }
    },
    // 查看第二步后面
    secondViewSubmit () {
      this.changeTab()
    },
    // 第二步保存
    secondSubmit () {
      // 先去校验考站是否已经维护好
      this.$refs.secondStep.checkInfoHandle()
    },
    // 国考第二步保存前先确认考站是否维护好了
    recordsSubmitBefore () {
      this.$refs.secondStep.checkInfoHandleNiMing()
    },
    secondHandleEndNiMing () {
      let params = {
        id: this.recordsId,
        ifAnonymous: 1
        // examStatus: 1
      }
      examRecordsSubmitA(params).then(res => {
        console.log(res)
        this.$message({
          message: '匿名考生添加成功',
          type: 'success'
        })
        this.activeIndex = 2
        this.changeTab()
      })
    },
    secondHandleEnd () {
      this.activeIndex = 2
      setTimeout(() => {
        // this.$refs.thirdStep.getStudentRandomization()
        this.$refs.thirdStep.getStudentList()
        this.$refs.thirdStep.getRecordsstationstudentList()
      }, 100)
    },
    recordsSubmit () {

    },
    // 第三步保存
    thirdSubmit () {
      this.$refs.thirdStep.thirdSubmitHandle()
    },
    changeTab () {
      if (this.firstForm.ifAnonymous === '1') {
        this.activeIndex = 2
        setTimeout(() => {
          this.$refs.forthStep.getRecordsDetail2()
        }, 10)
      } else {
        this.activeIndex = 3
        setTimeout(() => {
          this.$refs.forthStep.getRecordsDetail2()
          this.$emit('closeHandle', 'fresh')
        }, 10)
      }
    },
    // 重置数据
    resetData () {
      this.firstForm = {
        recordsName: '',
        examLocation: '',
        sountdownTime: '',
        examAddress: '',
        // 1:大分项 2:小分项
        examScoreSet: '2',
        examPoolId: '',
        examDate: [],
        // 学生库id
        studentPoolId: '',
        // 学生库name
        studentPool: '',
        teacherPool: '',
        examScoreMin: '0.5',
        ifSountdown: '0',
        ifSign: '0',
        ifAnonymous: '1',
        stationNumber: 5,
        teacherId: '',
        teacherName: '',
        password: '',
        checkPassword: '',
        passwordType: true
      }
      this.addFormData = {
        // 产品列表
        productList: [
          {
            examDateDay: '',
            startTime: '',
            endTime: ''
          }
        ]
      }
      this.firstStepDataList = [
        {
          examStartDate: '',
          examEndDate: '',
          teamCount: 3
        }
      ]
      this.activeIndex = 0
    },

    // 第一步
    changeFirstInfo () {
      this.addFormData.productList = []
      if (this.firstStepDataList.length > 0) {
        this.firstStepDataList.map(item => {
          this.addFormData.productList.push({
            examDateDay: item.examStartDate.substring(0, 10),
            startTime: item.examStartDate.substring(11, 16),
            endTime: item.examEndDate.substring(11, 16),
            teamCount: item.teamCount,
            id: item.id || '',
            examDateStatus: 0
          })
        })
      } else {
        this.dateRange(this.firstForm.examStartDate, this.firstForm.examEndDate)
      }
      this.firstForm.examDate = [this.firstForm.examStartDate, this.firstForm.examEndDate]
    },
    // 两天时间差
    daysBetween (date1, date2) {
      if (date1 && date2) {
        // 每天的毫秒数
        const oneDay = 24 * 60 * 60 * 1000
        const time1 = new Date(date1).getTime()
        const time2 = new Date(date2).getTime()

        const diffDays = Math.abs((time2 - time1) / oneDay) + 1

        return diffDays
      } else {
        return '暂无'
      }
    },
    // 获取学生库列表
    getList () {
      let params = {
        limit: 10000,
        page: 1,
        type: 'A类',
        orderSql: 'creat_date desc',
        studentPool: this.searchText || ''
      }
      fetchList(params).then(res => {
        this.studentPoolArr = res.data.page.records
      })
    },
    // 获取学生库列表
    getTeacherList () {
      let params = {
        limit: 10000,
        page: 1,
        orderSql: 'creat_date desc',
        teacherPool: this.searchTeacherText || ''
      }
      fetchTeacherList(params).then(res => {
        this.teacherPoolArr = res.data.page.records
      })
    },
    chooseStudent () {
      this.searchText = ''
      this.getList()
      this.chooseStudentShow = true
    },
    chooseTeacher () {
      this.searchTeacherText = ''
      this.getTeacherList()
      this.chooseTeacherShow = true
    },
    chooseTeacherHandle (item) {
      this.firstForm.teacherPoolId = item.id
      this.firstForm.teacherPool = item.teacherPool
      this.firstForm.teacherId = ''
      this.firstForm.teacherName = ''
      this.getTeacher()
      this.chooseTeacherShow = false
    },
    chooseHandle (item) {
      this.firstForm.studentPoolId = item.id
      this.firstForm.studentPool = item.studentPool
      this.firstForm.examLocation = item.examLocation
      this.firstForm.examAddress = item.examAddress
      // 备份考试日期
      let dateArrBak = []
      JSON.parse(item.time).map(item => {
        dateArrBak.push(item.substr(0, 10))
      })
      let dateArr = [...new Set(dateArrBak)]
      dateArr.sort((a, b) => {
        return new Date(a) - new Date(b)
      })
      if (dateArr.length === 1) {
        this.firstForm.examDate = [dateArr[0], dateArr[0]]
      } else {
        this.firstForm.examDate = dateArr
      }
      let timeArrBak = JSON.parse(item.time)
      timeArrBak.sort((a, b) => {
        return new Date(a.substr(0, 19)) - new Date(b.substr(0, 19))
      })

      this.addFormData = {
        productList: []
      }
      timeArrBak.map(v => {
        this.addFormData.productList.push({
          examDateDay: v.substr(0, 10),
          startTime: v.substring(11, 16),
          endTime: v.substring(33, 38),
           // 默认需要三组
          teamCount: 3
        })
      })
      this.chooseStudentShow = false
    },

    pestChange (e, index) {
      let data = this.addFormData.productList[index]
      Object.keys(data).forEach(key => {
        data[key] = e[key]
      })
      this.addFormData.productList[index].productCount = 1
    },
    handleUpdateYes (row) {
      // 拿到上一行数据再往数组中push（）新的数据
      this.addFormData.productList.push({
        examDateDay: row.examDateDay,
        startTime: row.startTime,
        endTime: row.endTime
        // examDateRange: row.examDateRange
      })
    },
    handleDeleteProduct (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.id) {
          this.addFormData.productList.splice(row.index, 1)
          recordsDateDelete([row.id]).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        } else {
          this.addFormData.productList.splice(row.index, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加订单表单提交
    handleSubmitAdd () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          console.log('aaa')
        }
      })
    },
    checkTimes (ranges) {
      const sortedRanges = ranges.sort((a, b) => Number(a.startTime.replace(':', '.')) - Number(b.startTime.replace(':', '.')))
      return sortedRanges.some((range, i) =>
        i > 0 && Number(range.startTime.replace(':', '.')) < Number(sortedRanges[i - 1].endTime.replace(':', '.')))
    },
    // 保存 第一步
    submitFirstHandle () {
      let trueFlag = false
      let aaa = JSON.parse(JSON.stringify(this.groupBy(this.addFormData.productList, 'examDateDay')))
      let bbb = []
      aaa.map(val => {
        bbb.push(val[1])
      })
      for (let i = 0; i < bbb.length; i++) {
        for (let q = 0; q < bbb[i].length; q++) {
          if (!bbb[i][q].startTime || !bbb[i][q].endTime || !bbb[i][q].examDateDay) {
            this.$message.warning('请检查日期或者时间是否为空')
            return
          }
        }
      }
      for (let k = 0; k < bbb.length; k++) {
        let qqq = this.checkTimes(bbb[k])
        if (qqq === true) {
          this.$message.warning('请检查时间范围是否正确')
          trueFlag = true
          return
        }
      }
      if (trueFlag === false) {
        this.$refs['firstForm'].validate((valid) => {
          if (valid) {
            let examRecordsEntity = JSON.parse(JSON.stringify(this.firstForm))
            examRecordsEntity.examStartDate = examRecordsEntity.examDate[0]
            examRecordsEntity.examEndDate = examRecordsEntity.examDate[1]
            // 草稿/待考试/已考试",0，1，2
            // examRecordsEntity.examStatus = 0
            examRecordsEntity.type = 'A类'
            if (this.firstForm.teacherId) {
              let teacherName = this.teacherArr.filter(v => {
                return v.id === this.firstForm.teacherId
              })[0].teacherName
              examRecordsEntity.teacherName = teacherName
            } else {
              delete examRecordsEntity.teacherName
            }
            let examRecordsDates = []
            let aaabbb = this.addFormData.productList.sort((a, b) => parseInt(new Date(`${a.examDateDay} ${a.startTime}:00`).getTime()) - parseInt(new Date(`${b.examDateDay} ${b.startTime}:00`).getTime()))
            aaabbb.map((item, index) => {
              examRecordsDates.push(
                {
                  examStartDate: `${item.examDateDay} ${item.startTime}:00`,
                  examEndDate: `${item.examDateDay} ${item.endTime}:00`,
                  id: item.id || '',
                  teamCount: item.teamCount,
                  examDateStatus: 0,
                  examOrder: index + 1
                }
              )
            })
            let params = {
              examRecordsEntity,
              examRecordsDates
            }
            if (params.examRecordsEntity.id) {
              if (this.firstForm.passwordType) {
                params.examRecordsEntity.password = this.firstForm.password
                params.examRecordsEntity.passwordType = '1'
              } else {
                params.examRecordsEntity.passwordType = '0'
              }
              if (this.passwordCheck !== '') {
                params.passwordCheck = this.passwordCheck
              }
              updateRecordsFirst(params).then(res => {
                if (res.data.code === 0) {
                  this.$message.success('第一步编辑成功')
                  setTimeout(() => {
                    this.activeIndex = 1
                    this.recordsId = params.examRecordsEntity.id
                    setTimeout(() => {
                      this.$refs.secondStep.getRecordsDetail2()
                    }, 100)
                  }, 1000)
                }
              })
            } else {
              if (this.firstForm.passwordType) {
                params.examRecordsEntity.password = this.firstForm.password
                params.examRecordsEntity.passwordType = '1'
              } else {
                params.examRecordsEntity.passwordType = '0'
              }
              params.examRecordsEntity.createUserName = this.userInfo.realName
              params.examRecordsEntity.createUserId = this.userInfo.id
              saveRecordsFirst(params).then(res => {
                if (res.data.code === 0) {
                  this.$message.success('第一步创建成功')
                  setTimeout(() => {
                    this.activeIndex = 1
                    if (this.firstForm.passwordType) {
                      this.passwordCheck = this.firstForm.password
                    }
                    this.recordsId = res.data.examRecordsId
                    setTimeout(() => {
                      this.$refs.secondStep.getRecordsDetail2()
                    }, 100)
                  }, 1000)
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  },

  watch: {
  }
}
</script>
<style lang='scss'>
.el-table .warning-row {
  background: #00b99e10;
}

.el-table .success-row {
  background: #ebf2f940;
}
.custom-table {
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #00b99e50;
  box-shadow: 0 0 5px #00b99e80;
}
/* 设置表头高度 */
.custom-table .el-table__header-wrapper .el-table__header {
  height: 20px !important; /* 你想要的高度 */
}
.custom-table thead .el-table__cell{
  height: 20px !important; /* 你想要的高度 */
  line-height: 20px !important; /* 你想要的高度 */
  background: #eeeeee;
  
}
.addExam{
  .el-dialog__body{
    padding: 0;
    .body-box{
      background: #fff;
      height: calc( 100vh - 46px );
      padding: 10px;
      flex-direction: column;
      overflow: auto;
      .top{
        width: 100%;
        height: 100px;
        position: fixed;
        top: 46px;
        left: 0;
        background-image: radial-gradient(transparent 1px, #ffffff 1px);
        background-size: 4px 4px;
        backdrop-filter: saturate(50%) blur(10px);
        -webkit-backdrop-filter: saturate(50%) blur(4px);
        z-index: 10;
        .top-inner{
          margin: 20px auto 0;
          height: 80px;
          min-width: 801px;
          max-width: 1000px;
          background-color: rgba(255,255,255,0.1);
        }
        
      }
      .mid{
        margin: 6px 0;
        padding: 8px;
        overflow: auto;
        .mid-inner{
          min-width: 801px;
          max-width: 1000px;
          margin: 80px auto 30px;
          padding: 15px 30px;
          background: #f5f5f5;
          min-height: calc(100vh - 210px);
          border-radius: 10px;

        }
        
      }
      .bot{
        height: 50px;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-image: radial-gradient(transparent 1px, #ffffff 1px);
        background-size: 4px 4px;
        backdrop-filter: saturate(50%) blur(10px);
        -webkit-backdrop-filter: saturate(50%) blur(4px);
        z-index: 10;
        .bot-inner{
          min-width: 801px;
          max-width: 1000px;
          margin: 10px auto 0;
          background-color: rgba(255,255,255,0.1);
        }
      }
    }
  }
}

</style>